package org.lc.service.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.lc.platform.mybatis.crud.service.impl.CrudBaseServiceImpl;
import org.lc.platform.mybatis.manager.query.QueryBuilder;
import org.lc.service.system.dto.SysPermissionDto;
import org.lc.service.system.entity.SysPermission;
import org.lc.service.system.entity.SysRolePermission;
import org.lc.service.system.mapper.SysPermissionMapper;
import org.lc.service.system.service.SysPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class SysPermissionServiceImpl extends CrudBaseServiceImpl<SysPermissionDto, SysPermission, SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Override
    public SysPermission Convertor(SysPermission data) {
        return data;
    }

    @Override
    public QueryBuilder<SysPermission> getQueryBuilder(SysPermissionDto query, QueryBuilder<SysPermission> queryBuilder) {
        queryBuilder.eq(query.getMenuId() != null, "menu_id", query.getMenuId());
        queryBuilder.like(query.getName() != null, "name", query.getName());
        return queryBuilder;
    }

    @Override
    public boolean getPermissionExits(String permission, String menuId) {
        var warp = new LambdaQueryWrapper<SysPermission>();
        warp.eq(permission != null, SysPermission::getCode, permission);
        warp.eq(menuId != null, SysPermission::getMenuId, menuId);
        return this.baseMapper.exists(warp);
    }

    @Override
    @Transactional
    public boolean batchRolePermission(String role, List<String> rp) {
        var wrap = Db.lambdaQuery(SysRolePermission.class).eq(SysRolePermission::getSysRoleId, role).getWrapper();
        if (Db.count(wrap) > 0) {
            Db.remove(wrap);
        }
        if (rp != null && !rp.isEmpty()) {
            List<SysRolePermission> rolePermission = rp.stream().map(r -> new SysRolePermission(role, r)).toList();
            return Db.saveBatch(rolePermission);
        }
        return true;

    }
}